import { cartListFn } from '@/api/cart'

export default {
  namespaced: true,
  state() {
    return {
      cartList: [],
    }
  },
  mutations: {
    setCartList(state, obj) {
      state.cartList = obj
    },
    toggleCheck(state, goodsId) {
      // console.log(222222222222222);

      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    quanxuan(state, flag) {
      state.cartList.map(item => item.isChecked = flag)
    },
    changeCount(state, { goodsId, value }) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = value
    },
    deleteFn(state) {
      state.cartList = state.cartList.filter(item => {
        return item.isChecked !== true
      })
    }
  },
  actions: {
    getCartAction(context) {
      cartListFn().then(res => {
        // console.log(res);
        // 返回回来的值不包括选中和不选中
        const { data: { cartTotal, list } } = res
        list.forEach(item => {
          item.isChecked = true
        })
        context.commit('setCartList', list)
      })
    },

  },
  getters: {
    // 购物车总数
    cartTotal(state) {
      return state.cartList.reduce((prev, current) => {
        return prev + current.goods_num
      }, 0)
    },
    // 购物车选中的List
    selCartList(state) {
      return state.cartList.filter(item => {
        return item.isChecked === true
      })
      // return
    },
    // 选中的总数
    selTotal(state, getters) {
      return getters.selCartList.reduce((prev, current) => {
        return prev + current.goods_num
      }, 0)
    },
    // 选中的总价
    selPrice(state, getters) {
      return getters.selCartList.reduce((prev, current) => {
        return prev + current.goods_num * current.goods.goods_price_min
      }, 0).toFixed(2)
    },

  },
}